import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from '../../entities/category.entity';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
  ) {}

  async findAll() {
    return this.categoryRepository.find({ order: { id: 'ASC' } });
  }

  async findOne(id: number) {
    return this.categoryRepository.findOne({ where: { id } });
  }

  async create(categoryData: Partial<Category>) {
    const category = this.categoryRepository.create(categoryData);
    return this.categoryRepository.save(category);
  }

  async update(id: number, categoryData: Partial<Category>) {
    await this.categoryRepository.update(id, categoryData);
    return this.categoryRepository.findOne({ where: { id } });
  }

  async remove(id: number) {
    await this.categoryRepository.delete(id);
    return { success: true };
  }

  async updateArticleCount(categoryId: number) {
    // 更新分类下的文章数量
    const query = `
      UPDATE category c 
      SET articleCount = (SELECT COUNT(*) FROM article a WHERE a.categoryId = c.id)
      WHERE c.id = ?
    `;
    await this.categoryRepository.query(query, [categoryId]);
  }

  async updateStatus(id: number, isActive: number) {
    // 检查分类是否存在
    const category = await this.categoryRepository.findOne({ where: { id } });
    if (!category) {
      throw new HttpException('分类不存在', HttpStatus.NOT_FOUND);
    }

    // 更新状态
    await this.categoryRepository.update(id, { isActive });
    
    // 返回更新后的分类
    return this.categoryRepository.findOne({ where: { id } });
  }
}
